package com.ptt.sqm.ws;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.ksoap2.serialization.PropertyInfo;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;
import android.widget.Toast;

/**
 * @author AndroidExample DotNetWebService Class
 * 
 */
@SuppressLint("NewApi")
public class UploadCall implements IDefaulCall {

	private static UploadCall singleton;

	public AsyncResponse delegate = null;

	public static UploadCall getInstance() {
		if (singleton == null) {
			singleton = new UploadCall();
		}

		return singleton;
	}

	public UploadCall() {
	}

	public Object execute(String method, PropertyInfo[] params) {
		String fileName = (String) params[0].getValue();
		Bitmap sourceFile = (Bitmap) params[1].getValue();

		HttpURLConnection conn = null;
		DataOutputStream dos = null;
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;
		int maxBufferSize = 1 * 1024 * 1024;

		try {

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			sourceFile.compress(CompressFormat.JPEG, 75, bos);
			buffer = bos.toByteArray();
		
			// open a URL connection to the Servlet
			//FileInputStream fileInputStream = new FileInputStream(sourceFile);
			URL url = new URL(method);

			// Open a HTTP connection to the URL
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true); // Allow Inputs
			conn.setDoOutput(true); // Allow Outputs
			conn.setUseCaches(false); // Don't use a Cached Copy
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("ENCTYPE", "multipart/form-data");
			conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			conn.setRequestProperty("uploaded_file", fileName);

			dos = new DataOutputStream(conn.getOutputStream());

			dos.writeBytes(twoHyphens + boundary + lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd);

			dos.writeBytes(lineEnd);

			// create a buffer of maximum size
//			bytesAvailable = fileInputStream.available();

			bufferSize = buffer.length;
			//buffer = new byte[bufferSize];

			// read file and write it into form...
			//bytesRead = fileInputStream.read(buffer, 0, bufferSize);

			//while (bytesRead > 0) {

				dos.write(buffer, 0, bufferSize);
				dos.flush();
//				bytesAvailable = fileInputStream.available();
//				bufferSize = Math.min(bytesAvailable, maxBufferSize);
//				bytesRead = fileInputStream.read(buffer, 0, bufferSize);

			//}

			// send multipart form data necesssary after file data...
			dos.writeBytes(lineEnd);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

			// Responses from the server (code and message)
			int serverResponseCode = conn.getResponseCode();
			String serverResponseMessage = conn.getResponseMessage();

			Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

			if (serverResponseCode == 200) {
				return String.valueOf(serverResponseCode);
			}

			// close the streams //
			//fileInputStream.close();
			dos.flush();
			dos.close();

		} catch (MalformedURLException ex) {

			ex.printStackTrace();
			Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
		} catch (Exception e) {

			e.printStackTrace();
			Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
		}
		return String.valueOf(0);

	}

}
